package path;

/**
 * 二、路径问题
 * 4. 下降路径最小和
 * 2024-10-19
 */
public class demo8 {
    public int minFallingPathSum(int[][] matrix) {
        //1. 创建 dp 表
        int n = matrix.length;
        int[][] dp = new int[n+1][n+2];

        //2. 初始化
        for (int i = 1; i <= n; i++) {
            //第一列和最后一列
            dp[i][0] = dp[i][n+1] = Integer.MAX_VALUE;
        }

        //3. 填表
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[i-1][j], dp[i-1][j+1])) + matrix[i-1][j-1];
            }
        }
        int ret = Integer.MAX_VALUE;
        for (int i = 1; i <= n; i++) {
            ret = Math.min(ret, dp[n][i]);
        }
        return ret;
    }
}
